package com.stoneapple.timesheet.dao;


import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import com.stoneapple.timesheet.entity.Timesheet;

public class TSDao {
	private static TSDao instance;

	private TSDao() {
	}

	public static TSDao getInstance() {
		if (instance == null) {
			instance = new TSDao();
		}
		return instance;
	}

	
	@SuppressWarnings("unchecked")
	public List<Timesheet> getTSList() {
		EntityManager em = EMF.get().createEntityManager();
		Query query = em.createQuery("SELECT * FROM Timesheet ");
		List<Timesheet> timesheet = query.getResultList();
		return timesheet;
	}

	@SuppressWarnings("unchecked")
	public List<Timesheet> getTSListByUserId(String userId) {
		EntityManager em = EMF.get().createEntityManager();
		Query query = em.createQuery("SELECT T FROM Timesheet T WHERE author = :userId");
		query.setParameter("userId", userId);
		List<Timesheet> timesheet = query.getResultList();
		return timesheet;
	}

	public void save (String userId,String projectcode, String assignmentname, int hours ) {
		synchronized (this) {
			EntityManager em = EMF.get().createEntityManager();
			Timesheet timesheet=new Timesheet(userId, projectcode, assignmentname, hours);
			try {
				em.persist(timesheet);
			} finally {
				em.close();
			}
		}
	}

	public void delete(Long id) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			Timesheet timesheet = em.find(Timesheet.class, id);
			em.remove(timesheet);
		} finally {
			em.close();
		}
	}

}
